<?php
if (!defined('ABSPATH')) {
    exit();
}
if (!class_exists('CMC_cronjob')) {
    class CMC_cronjob
    {

        public function __construct()
        {
         
        }

        public function cmc_cron_init_hooks()
        {

            //initialize Cron Jobs
            add_filter('cron_schedules', array($this, 'cmc_cron_schedules'));
            add_action('cmc_coins_autosave', array($this, 'do_this_5minutes_updates'));
            add_action('cmc_coins_autosave_over_250', array($this, 'do_this_1_day_after'), 10);
            add_action('cmc_extra_data_update', array($this, 'cmc_cron_extra_data_autoupdater'));

        }
        
        function cmc_cron_extra_data_autoupdater() {
       
            $settings       = get_option('openexchange-api-settings', []);
            $ccpw_response  = isset($settings['cmc_extra_info']) ? $settings['cmc_extra_info'] : '';
          
            if ($ccpw_response === 'on') {
            
                if (class_exists('CMC_cronjob')) {
                    CMC_cronjob::cmc_send_data();
                }
            }
        }

        static public function cmc_send_data() {
            $feedback_url = CMC_FEEDBACK_API.'wp-json/coolplugins-feedback/v1/site';
            $extra_data_details = cpfm_get_user_info();
            
            $server_info    = $extra_data_details['server_info'];
            $extra_details  = $extra_data_details['extra_details'];
            $site_url       = get_site_url();
            $install_date   = get_option('cmc-install-date');
            $unique_key     = '1';  // Ensure this key is unique per plugin to prevent collisions when site URL and install date are the same across plugins
            $site_id        = $site_url . '-' . $install_date . '-' . $unique_key;
            $initial_version = get_option('cmc_initial_save_version');
            $initial_version = is_string($initial_version) ? sanitize_text_field($initial_version) : 'N/A';
            $plugin_version = defined('CMC') ? CMC : 'N/A';
            $admin_email    = sanitize_email(get_option('admin_email') ?: 'N/A');
            
            $post_data = array(
                
                'site_id'           => md5($site_id),
                'plugin_version'    => $plugin_version,
                'plugin_name'       => 'Coin Market Cap',
                'plugin_initial'    => $initial_version,
                'email'             => $admin_email,
                'site_url'          => esc_url_raw($site_url),
                'server_info'       => $server_info,
                'extra_details'     => $extra_details,
            );
            
            $response = wp_remote_post($feedback_url, array(      
                'method'    => 'POST',
                'timeout'   => 30,
                'headers'   => array(
                    'Content-Type' => 'application/json',
                ),
                'body'      => wp_json_encode($post_data),
            ));

            if (is_wp_error($response)) {

                error_log('CMC Feedback Send Failed: ' . $response->get_error_message());
                return;
            }
            
            $response_body  = wp_remote_retrieve_body($response);
            $decoded        = json_decode($response_body, true);
            
            if (!wp_next_scheduled('cmc_extra_data_update')) {

                wp_schedule_event(time(), 'every_30_days', 'cmc_extra_data_update');
            }
        }

        /*
        |--------------------------------------------------------------------------
        |   on plugin activation hook adding page and flushing rewrite rules
        |--------------------------------------------------------------------------
         */
        public function cmc_cron_job_init()
        {

            if (cmc_check_required_settings()) {

                if (!wp_next_scheduled('cmc_coins_autosave')) {
                    if (wp_next_scheduled('ccpwp_coins_autosave')) {
                        wp_clear_scheduled_hook('ccpwp_coins_autosave');
                    }
                    wp_schedule_event(time(), '5min', 'cmc_coins_autosave');
                }
                if (!wp_next_scheduled('cmc_coins_autosave_over_250')) {
                    if (wp_next_scheduled('ccpw_coins_autosave_over250')) {
                        wp_clear_scheduled_hook('ccpw_coins_autosave_over250');
                    }
                    wp_schedule_event(strtotime("+5 seconds"), '1day', 'cmc_coins_autosave_over_250');
                }

            }

        }

/*
|--------------------------------------------------------------------------
|  cron custom schedules
|--------------------------------------------------------------------------
 */
        public function cmc_cron_schedules($schedules)
        {
            // 5 minute schedule for grabing all coins
            if (!isset($schedules["5min"])) {
                $schedules["5min"] = array(
                    'interval' => 5 * 60,
                    'display' => __('Once every 5 minutes'),
                );
            }
            if (!isset($schedules["1day"])) {
                $schedules["1day"] = array(
                    'interval' => 43200 * 2,
                    'display' => __('Once every days'),
                );
            }
            if (!isset($schedules['every_30_days'])) {

                $schedules['every_30_days'] = array(
                    'interval' => 30 * 24 * 60 * 60, // 2,592,000 seconds
                    'display'  => __('Once every 30 days'),
                );
            }


            return $schedules;
        }
/*
|--------------------------------------------------------------------------
|  grabing coins data after 5 minute using cron
|--------------------------------------------------------------------------
 */

        public function do_this_5minutes_updates()
        {
            //saving all coins data
            CMC_api_data::cmc_get_selected_api_data();

        }

/*
|--------------------------------------------------------------------------
| grabing coin weekly price data(historical)for small charts
|--------------------------------------------------------------------------
 */
        public function do_this_1_day_after()
        {
            $api_option = get_option("openexchange-api-settings");
            $api_type = (isset($api_option['select_api'])) ? $api_option['select_api'] : "coingecko";
            for ($page = 2; $page <= 5; $page++) {
                CMC_api_data::cmc_get_selected_api_data($page);

            }
            sleep(60);
            for ($page = 6; $page <= 10; $page++) {
                CMC_api_data::cmc_get_selected_api_data($page);

            }
            if ($api_type == "coinmarketcap" || $api_type == "both_coinmarketcap") {
                CMC_api_data::cmc_get_selected_api_data(11);
                CMC_api_data::cmc_get_selected_api_data(12);
                CMC_api_data::cmc_get_selected_api_data(13);

            }
            $DB = new CMC_Coins();
            $DB->cmc_refresh_db();
        }

    }
}
